package com.caineng.zhaobiao.zbapi.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.caineng.zhaobiao.zbapi.controller.paramVo.CaiZhaobiaoVo;
import com.caineng.zhaobiao.zbapi.dao.CaiZhaobiaoDao;
import com.caineng.zhaobiao.zbapi.domain.CaiBaseUser;
import com.caineng.zhaobiao.zbapi.domain.CaiZhaobiao;
import com.caineng.zhaobiao.zbapi.domain.CaiZhaobiaoDetail;
import com.caineng.zhaobiao.zbapi.interceptor.logs.BusinessType;
import com.caineng.zhaobiao.zbapi.interceptor.logs.CainengApiLog;
import com.caineng.zhaobiao.zbapi.service.*;
import com.caineng.zhaobiao.zbapi.service.vo.ZhaobiaoVo;
import com.caineng.zhaobiao.zbapi.utils.AjaxResult;
import com.caineng.zhaobiao.zbapi.utils.email.MyEmailBean;
import com.caineng.zhaobiao.zbapi.utils.email.MyEmailUtil;
import com.caineng.zhaobiao.zbapi.utils.enums.USER_ACTION;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 招标服务类
 * @author liandyao
 * @date 2022/7/18 15:46
 */
@Slf4j
@Api(tags = "招标服务模块")
@RestController
@RequestMapping("/zbapi/zhaobiao")
public class CaiZhaobiaoController {

    @Autowired
    CaiZhaobiaoDao zbDao ;

    @Autowired
    CaiZhaobiaoService zhaobiaoService;

    @Autowired
    CaiCommentService commentService;

    @Autowired
    MyEmailUtil mailUtil;

    @Autowired
    UserService userService;

    @Autowired
    CaiZhaobiaoDetailService detailService ;

    @Autowired
    CaiSystemConfigService systemConfigService ;

    @Autowired
    MongoTemplate mongoTemplate;


    @GetMapping("/findAll")
    @ApiOperation(value = "0001 查询所有的招标信息")
    public AjaxResult findAll(CaiZhaobiaoVo zb){
        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize(),Sort.Direction.DESC,"createTime");
        //自己封装分页对象
        List<ZhaobiaoVo> list = zhaobiaoService.findAll(zb,page);
        Page records = new PageImpl(list,page,1000);
        return AjaxResult.success("成功",records);

    }

    @GetMapping("/findCustomMade")
    @ApiOperation(value = "查询订阅的招标信息")
    public AjaxResult findCustomMade(CaiZhaobiaoVo zb){

        String userId = StpUtil.getLoginIdAsString();

        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize(),Sort.Direction.DESC,"createTime");
        //自己封装分页对象
        List<ZhaobiaoVo> list = zhaobiaoService.findCustomMade(zb,page,userId);
        Page records = new PageImpl(list,page,1000);
        return AjaxResult.success("成功",records);

    }

    @GetMapping("/findOne")
    @ApiOperation(value = "0010 根据id查询招标信息")
    public AjaxResult findOne(String id){

        Optional<CaiZhaobiao> byId =zbDao.findById(id);
        CaiZhaobiao zhaobiao = byId.orElse(null);
        if(zhaobiao==null){
            return AjaxResult.error("您查看的招标找不到了");
        }

        boolean found = detailService.isMaxCount();
        if(!found){
            return AjaxResult.error("今日查看已达到上限!");
        }

        //加入详情信息
        CaiZhaobiaoDetail detail = detailService.findByBusId(zhaobiao.getId());
        if(detail!=null){
            zhaobiao.setNoticeContent(detail.getContent());
        }
        return AjaxResult.success("ok",zhaobiao);
    }

    @GetMapping("/findDetail")
    @ApiOperation(value = " 0020 根据id查询招标信息-新的方法,使用自己的id作为主键")
    public AjaxResult findDetail(String id){

        CaiZhaobiao zhaobiao =zhaobiaoService.findByMyId(id);
        if(zhaobiao==null){
            return AjaxResult.error("您查看的招标找不到了");
        }

        boolean found = detailService.isMaxCount();
        if(!found){
            return AjaxResult.maxLimitByDay("今日查看已达到上限!");
        }

        //加入详情信息,一般不需要查详情,因为占用网络流量太多
        CaiZhaobiaoDetail detail = detailService.findByBusId(zhaobiao.getId());
        if(detail!=null){
            zhaobiao.setNoticeContent(detail.getContent());
        }
        return AjaxResult.success("ok",zhaobiao);
    }

    @GetMapping("/findZbProperty")
    @ApiOperation(value = "0030 根据id查询解析的招标属性")
    public AjaxResult findZbProperty(String id){

        Map map = zhaobiaoService.findZbProperty(id);
        return AjaxResult.success("ok",map);
    }


    @PostMapping("/viewCount/{id}")
    @ApiOperation(value = "招标浏览数+1 传入的参数为招标id" )
    public AjaxResult viewCount(@PathVariable("id") String id){

        CaiZhaobiao zhaobiao =zhaobiaoService.findByMyId(id);


        if(zhaobiao==null){
            return AjaxResult.error("招标id不存在");
        }
        //将浏览次数+1
        zhaobiaoService.addCountInc(USER_ACTION.view,id) ;

/*        Integer viewCount = zhaobiao.getViewCount();
        if(viewCount==null) {
            zhaobiao.setViewCount(1);
        }else{
            zhaobiao.setViewCount(viewCount+1);
        }
        //保存招标数据
        zbDao.save(zhaobiao);*/

        //是否登录,如果已经登录,则记住自己的浏览记录
        if(StpUtil.isLogin()){
            String userId = StpUtil.getLoginIdAsString();
            commentService.addUserAction(id, USER_ACTION.view.name(), userId);
        }
        return AjaxResult.success("ok",zhaobiao);
    }

    @PostMapping("/favCount/{id}")
    @ApiOperation(value = "招标收藏数+1" )
    public AjaxResult favCount(@PathVariable("id") String id){

        CaiZhaobiao zhaobiao =zhaobiaoService.findByMyId(id);
        if(zhaobiao==null){
            return AjaxResult.error("招标id不存在");
        }
        zhaobiaoService.addCountInc(USER_ACTION.fav,id);
        /*Integer viewCount = zhaobiao.getFavCount();
        if(viewCount==null) {
            zhaobiao.setFavCount(1);
        }else{
            zhaobiao.setFavCount(viewCount+1);
        }
        //保存招标数据
        zbDao.save(zhaobiao);*/

        //是否登录,如果已经登录,则可以收藏
        if(StpUtil.isLogin()){
            String userId = StpUtil.getLoginIdAsString();

            int resulet = commentService.addUserAction(zhaobiao.getId(), USER_ACTION.fav.name(), userId);
            if(resulet==10){
                return AjaxResult.error("数据库已存在!");
            }
        }
        return AjaxResult.success("ok",zhaobiao);
    }

    @PostMapping("/deleteFavCount/{id}")
    @ApiOperation(value = "取消招标收藏" )
    public AjaxResult deleteFavCount(@PathVariable("id") String id){

        //是否登录,如果已经登录,则删除
        if(StpUtil.isLogin()){
            String userId = StpUtil.getLoginIdAsString();

            commentService.deleteZbIdByUserId(userId,id,USER_ACTION.fav.name());
        }
        return AjaxResult.success("ok");
    }


    @PostMapping("/deleteDiggCount/{id}")
    @ApiOperation(value = "取消招标点赞" )
    public AjaxResult deleteDiggCount(@PathVariable("id") String id){

        //是否登录,如果已经登录,则删除
        if(StpUtil.isLogin()){
            String userId = StpUtil.getLoginIdAsString();

            commentService.deleteZbIdByUserId(userId,id,USER_ACTION.digg.name());
        }
        return AjaxResult.success("ok");
    }

    @PostMapping("/diggCount/{id}")
    @ApiOperation(value = "招标点赞数+1" )
    public AjaxResult diggCount(@PathVariable("id") String id){

        CaiZhaobiao zhaobiao =zhaobiaoService.findByMyId(id);
        if(zhaobiao==null){
            return AjaxResult.error("招标id不存在");
        }
        zhaobiaoService.addCountInc(USER_ACTION.digg,id);

        //是否登录,如果已经登录,则可以收藏
        if(StpUtil.isLogin()){
            String userId = StpUtil.getLoginIdAsString();
            commentService.addUserAction(id, USER_ACTION.digg.name(), userId);
        }
        return AjaxResult.success("ok",zhaobiao);
    }

    @PostMapping("/sendEmail/{id}")
    @ApiOperation(value = "发送到邮箱" )
    @CainengApiLog(title="zhaobiao-发送到邮箱", businessType = BusinessType.INSERT)
    public AjaxResult sendEmail(@PathVariable("id") String id){

        String userId = StpUtil.getLoginIdAsString();
        CaiBaseUser user = userService.findUserById(userId);
        String email = user.getEmail();
        if(StrUtil.isBlank(email)){
            AjaxResult res=AjaxResult.error("您还没有填写邮箱地址");
            res.setCode("509"); //用户信息没有邮箱地址
            return res;
        }
        CaiZhaobiao zhaobiao =zhaobiaoService.findByMyId(id);

        if(zhaobiao==null){
            return AjaxResult.error("招标id不存在");
        }
        MyEmailBean mb=new MyEmailBean();
        mb.setRecipient(email); //收件人
        mb.setSubject("朋利招标-"+zhaobiao.getNoticeTitle());
        String content = "<h3><a href='"+zhaobiao.getUrlPath()+"'>点击查看招标原文: "+zhaobiao.getUrlPath()+"</a></h3>";


        content+="<h3>发布时间: "+zhaobiao.getPublishTime()+"</h4>";
        if(StrUtil.isNotBlank(zhaobiao.getBidFilePath())){
            if(StrUtil.containsAny(zhaobiao.getBidFilePath(),".pdf",".doc",".docx",".xls","xlsx",".jpg",".png",".gif",".jpeg",".bmp",".ppt",".pptx")){
                content+="<h3>附件下载:<a href='"+zhaobiao.getBidFilePath()+"'>点击查看附件</a></h3>" ;
            }else{
                String pdfView = "<embed width='700px' height='570px'  src='"+zhaobiao.getBidFilePath()+"' type='application/pdf'>";
                content+=pdfView ;
            }
        }


        //加入详情信息,一般不需要查详情,因为占用网络流量太多
        CaiZhaobiaoDetail detail = detailService.findByBusId(zhaobiao.getId());
        if(detail!=null){
            content += detail.getContent();
        }
        //上海地区的url访问加密了,并且上海地区是没有附件的。
        if(StrUtil.contains(zhaobiao.getUrlPath(),"shggzy.com")){
            content = detail.getContent();
        }

        content+="<p>朋利招标祝您马到成功(<a href='https://www.cspengli.com'>朋利招标</a>)</p>";

        mb.setContent(content);
        boolean bool = mailUtil.sendHTMLMail(mb);
        if(bool) {
            return AjaxResult.success("ok", email);
        }else{
            return AjaxResult.error("系统繁忙，请稍候再试！");
        }
    }




}
